<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" :label-position="labelPosition" label-width="110px">

        <el-row>
          <el-col :span="5">
            <el-form-item label="机构类型">
              <el-select value="国家机关" placeholder="机构类型">
                <el-option label="国家机关" value="国家机关" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="行政区域">
              <el-select value="内蒙古自治区" placeholder="行政区域">
                <el-option label="内蒙古自治区" value="内蒙古自治区" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="能源指标">
              <el-select value="总消耗量" placeholder="能源指标">
                <el-option label="总消耗量" value="总消耗量" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="统计数量">
              <el-select value="10" placeholder="统计数量">
                <el-option label="10" value="10" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="5">
            <el-form-item label="填报类型">
              <el-select value="月报" placeholder="填报类型">
                <el-option label="月报" value="月报" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="年月">
              <el-select value="2020" placeholder="年" style="width: 100px;">
                <el-option label="2020" value="2020" />
              </el-select>
              <el-select value="12" placeholder="月" style="width: 100px;">
                <el-option label="12" value="12" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="时间范围">
              <el-select value="2020" placeholder="年" style="width: 95px;" disabled>
                <el-option label="2020" value="2020" />
              </el-select>
              -
              <el-select value="12" placeholder="月" style="width: 95px;" disabled>
                <el-option label="2020" value="shanghai" />
                <el-option label="2019" value="shanghai" />
                <el-option label="2018" value="shanghai" />
                <el-option label="2017" value="shanghai" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label=" ">
              <el-checkbox v-model="checked1" label="时间范围" border style="width: 200px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="5">
            <el-form-item label="能源类型">
              <el-cascader
                :options="options1"
                :props="props"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label=" ">
              <el-checkbox v-model="checked1" label="统计含下级区域" border style="width: 200px;" />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleAudit">
            查询
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-s-data" @click="handleCreate">
            导出excel
          </el-button>
        </el-row>
      </el-form>

    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="区域名称" min-width="50" align="left">
        <template slot-scope="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位名称" min-width="100">
        <template slot-scope="{row}">
          <el-link type="danger" @click="handleUpdate(row)">{{ row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="150" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总消耗量（吨标煤）" class-name="status-col" width="180" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>s
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="$t('table.type')" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.date')" prop="timestamp">
          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="Please pick a date" />
        </el-form-item>
        <el-form-item :label="$t('table.title')" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item :label="$t('table.importance')">
          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />
        </el-form-item>
        <el-form-item :label="$t('table.remark')">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  createBaseInfo,
  updateBaseInfo
} from '@/api/base-info'

import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [{
  key: 'CN',
  display_name: 'China'
},
{
  key: 'US',
  display_name: 'USA'
},
{
  key: 'JP',
  display_name: 'Japan'
},
{
  key: 'EU',
  display_name: 'Eurozone'
}
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: {
    Pagination
  },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        待审: 'danger',
        已审: 'success'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      checked1: false,
      labelPosition: 'right',
      options: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }, {
        value: '选项3',
        label: '蚵仔煎'
      }, {
        value: '选项4',
        label: '龙须面'
      }, {
        value: '选项5',
        label: '北京烤鸭'
      }],
      value: '',
      formInline: {
        user: '',
        region: '',
        querySymbol: ''
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      statusOptions: [{
        label: '全部',
        key: ''
      }, {
        label: '退回',
        key: '0'
      }, {
        label: '草稿',
        key: '1'
      }, {
        label: '待审',
        key: '2'
      }, {
        label: '已审',
        key: '3'
      }],
      symbolOptions: [{
        label: '>=',
        key: ''
      }, {
        label: '<',
        key: '0'
      }, {
        label: '>',
        key: '1'
      }, {
        label: '<=',
        key: '2'
      }, {
        label: '=',
        key: '3'
      }],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{
          required: true,
          message: 'type is required',
          trigger: 'change'
        }],
        timestamp: [{
          type: 'date',
          required: true,
          message: 'timestamp is required',
          trigger: 'change'
        }],
        title: [{
          required: true,
          message: 'title is required',
          trigger: 'blur'
        }]
      },
      downloadLoading: false,
      props: { multiple: true },
      options1: [{
        value: 0,
        label: '全部',
        children: [
          { value: 1,
            label: '电'
          },
          {
            value: 2,
            label: '煤炭'
          },
          {
            value: 3,
            label: '天然气'
          },
          {
            value: 4,
            label: '汽油',
            children: [
              { value: 4 - 1, label: '车辆用油量' },
              { value: 4 - 2, label: '其他用油量' }
            ]
          },
          {
            value: 5,
            label: '柴油',
            children: [
              { value: 5 - 1, label: '车辆用油量' },
              { value: 5 - 2, label: '其他用油量' }
            ]
          },
          {
            value: 6,
            label: '液化石油气'
          },
          {
            value: 7,
            label: '热力'
          },
          {
            value: 8,
            label: '其他能源'
          }
        ]
      }]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      //    this.resetTemp()
      //    this.dialogStatus = 'create'
      //    this.dialogFormVisible = true
      //    this.$nextTick(() => {
      //      this.$refs['dataForm'].clearValidate()
      //    })

      this.$router.push({
        path: '/baseInfo/createBaseInfo1'
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createBaseInfo(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateBaseInfo(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleAudit(row, index) {
      this.$router.push({
        path: '/baseInfo/auditBaseInfo'
      })
    }
  }
}
</script>
